package Servlet.Admin;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Creche.Admin.Administrateur;
import Creche.Bd.BD;
import Form.MailForm;

@SuppressWarnings("serial")
public class Mail extends HttpServlet {
	
	public static final String VUE = "/WEB-INF/mail.jsp";
	public static final String MAIL = "mail";
	public static final String ADMIN = "admin";
	
	//private static final String HOST = "smtp.gmail.com";
	private static final String FROM = "pks@crechebook10.mygbiz.com";
	private static final String SUBJECT = "Mots de passe";
	//private static final String PASS = "l3infopks";
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException {
		
		/* Affichage de la page mail */
		this.getServletContext().getRequestDispatcher( VUE ).forward(req, resp);
	}
	
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException {
		
		BD myBD = new BD();
		MailForm mail = new MailForm();
        Administrateur admin = mail.verifierAdmin(req);
        
        req.setAttribute(MAIL, mail);
        req.setAttribute(ADMIN, admin);
		
		if (mail.getErreurs().isEmpty()) {
			
			String to = admin.getEmail();
			String body = "Voici vos mots de passe :\n\n" + 
						  "Votre identifiant : " + myBD.getAdmin(to).getIdentifiant() + "\n" +
						  "Votre mot de passe : " + myBD.getAdmin(to).getMotDePasse();
			
			try {
	            //mail.connect(HOST, FROM, PASS);
	            mail.send(FROM, to, SUBJECT, body);
	            
	        } catch (AddressException e) {
	        	Logger.getLogger(MailForm.class.getName()).log(Level.SEVERE, null, e);
	        	
	        } catch (MessagingException ex) {
	            Logger.getLogger(MailForm.class.getName()).log(Level.SEVERE, null, ex);
	        }
		}
		
		/* Transmission de la paire d'objets request/response à notre JSP */	
		this.getServletContext().getRequestDispatcher( VUE ).forward(req, resp);
	}
}